// pages/sceneTaskDetail/index.js
const api = require('../../config/api')
const request = require('../../utils/request')
const app = getApp()
let handleNext = false
import lottie from '../../utils/lottie'
const { getBarAndTitleHeight } = require('../../utils/util')
const {
	saveImage
} = require('../../utils/photo')
var sysInfo = wx.getSystemInfoSync()
let windowHeight = sysInfo.windowHeight
let scale = windowHeight / 667 //不同屏幕下canvas的适配比例；设计稿是750宽
const env = __wxConfig.envVersion
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: '', // 场景训练任务详情
    detail: '', // 任务详情
    posterSrc:
      'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend3112705936ec4679ad331a5d1cac2faf.png', // 海报图片
    showPoster: false,
    hadLogin: app.isLogin(), // 判断是否已登录
    shareInfo: {},
    trainingId: '',
    description: '',
    finishTaskShow: false,
    ...getBarAndTitleHeight(true),
    completeNum: '',
    programName: '',
    canShow: false,
    scale: scale,
    bottomHeight: app.kBottomSafeHeight + 112,
    modalHeight: app.kBottomSafeHeight + 345,
    barTitle: '任务详情',
    // 跳转来源
    origin: 0,
    env: env,
    fromOrigin: 0,// 从活动训练还是普通训练进入
    activityId: '',// 从活动训练训练进入接收活动id
    posterImg: 'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zhiliao-applet/CmcFNMinKpDV8835b43bb6765ed5d0aaa8d699de15d4.png', // 海报图片
    codeImg: '', // 用户小程序码
    imagePath: '',
    canvasHeight: 0,
    canvasWidth: 0,
    canvasLeft: 0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.init()
    this.setData({
      id: options.id,
      origin: Number(options?.origin),
      fromOrigin: Number(options?.fromOrigin) || 0,
      activityId: options?.activityId || '',
      ...getBarAndTitleHeight(),
    })

    console.log(options?.fromOrigin,options?.activityId)
    wx.hideNavigationBarLoading({
      success: (res) => {},
    })
    if(options?.activityId){
      this.getQRCode()
    }
  },
  onShow: function () {
    let { id } = this.data
    this.getTrainDetail(id)
    handleNext = false
  },
  savePhoto: function () {
		let that = this
		let {
			posterImg,
			codeImg
		} = that.data
		wx.downloadFile({
			url: posterImg,
			success(res) {
				console.log('downloadFile','sucess');
				const ctx = wx.createCanvasContext('myCanvas', that)
				wx.getImageInfo({
					src: posterImg,
					success: function (res) {
						// 绘制背景海报到canvas
						var sysInfo = wx.getSystemInfoSync()
						let windowWidth = sysInfo.windowWidth
						var scale = (windowWidth / 375) * 0.92 //不同屏幕下canvas的适配比例；设计稿是750宽
						let imgW = 274 * scale // 274
						let imgH = 407 * scale // 407
						let imgPath = res.path
						let codeSize = 80 * scale

						that.setData({
							canvasHeight: imgH,
							canvasWidth: imgW,
							canvasLeft: (windowWidth - imgW) / 2,
						})
						ctx.drawImage(imgPath, 0, 0, imgW, imgH)
						wx.getImageInfo({
							src: codeImg,
							success: function (res) {
								// 图片的x坐标
								let bg_x = (imgW - codeSize) / 2 // 10
								// 图片的y坐标
								let bg_y = imgH - codeSize - 35 // 70
								// 图片宽度
								let bg_w = codeSize
								// 图片高度
								let bg_h = codeSize
								// 图片圆角
								let bg_r = 6
								// 绘制海报背景图片圆角
								ctx.save()
								ctx.beginPath()
								ctx.arc(bg_x + bg_r, bg_y + bg_r, bg_r, Math.PI, Math.PI * 1.5)
								ctx.arc(bg_x + bg_w - bg_r,bg_y + bg_r,bg_r,Math.PI * 1.5,Math.PI * 2)
								ctx.arc(bg_x + bg_w - bg_r,bg_y + bg_h - bg_r,bg_r,0,Math.PI * 0.5)
								ctx.arc(bg_x + bg_r,bg_y + bg_h - bg_r,bg_r,Math.PI * 0.5,Math.PI)
								ctx.clip()
								ctx.drawImage(res.path, bg_x, bg_y, bg_w, bg_h)
								ctx.draw()
								setTimeout(() => {
									wx.canvasToTempFilePath({
											canvasId: 'myCanvas',
											success: function (res) {
												that.setData({
													imagePath: res.tempFilePath,
												})
											},
											fail: function (res) {},
										},
										this
									)
								}, 1000)
							},
						})
					},
				})
			},
		})
	},
	// 生成小程序码
	async getQRCode() {
		let {activityId} = this.data
		if(activityId){
			const res = await request.get(
				api.createQrcodeImg, {
					activityId: activityId,
				}, {
					loading: false
				}
			)
			if (res.httpStatus === 200) {
				this.setData({
					codeImg: res.data,
				})
				this.savePhoto()
			}
		}
	},
	// 保存海报
	handleSave() {
		wx.showLoading({
			title: '保存中...',
			mask: true
		})
		setTimeout(() => {
			wx.hideLoading()
			let {
				imagePath
			} = this.data
			saveImage(imagePath)
		}, 1500)
	},
  // 初始化加载动画
  init() {
    if (this.inited) {
      return
    }
    wx.createSelectorQuery()
      .selectAll('#lottie_view')
      .node((res) => {
        const canvas = res[0].node
        const context = canvas.getContext('2d')
        canvas.width = 500
        canvas.height = 500
        lottie.setup(canvas)

        this.ani = lottie.loadAnimation({
          loop: true,
          autoplay: true,
          animationData: require('./data.js'),
          rendererSettings: {
            context,
          },
        })
        this.inited = true

        setTimeout(()=>{
          wx.vibrateShort({
            type: 'light',
          })
        },1400)
        setTimeout(()=>{
          wx.vibrateShort({
            type: 'light',
          })
        },1700)
      })
      .exec()
  },
  // 获取训练任务详情
  getTrainDetail: async function (id) {
    const res = await request.get(
      api.trainingTaskDetail + id,
      {},
      { loading: false }
    )
    if (res.httpStatus === 200) {
      res.data.startDate = res.data?.startDate?.split(' ')[0]
      res.data.completionDate = res.data?.completionDate?.split(' ')[0]

      let htmlContent = res.data.trainingProgramDO.description

      if (htmlContent) {
        htmlContent = htmlContent.replace(
          new RegExp('<img', 'g'),
          '<img style="max-width:100%;height:auto"  '
        )
        htmlContent = htmlContent.replace(
          new RegExp('<video', 'g'),
          '<video style="width:100%;height:auto"  '
        )
        htmlContent = htmlContent.replace(
          new RegExp('<iframe', 'g'),
          '<iframe  width="100%"  '
        )
      }

      this.setData({
        detail: res.data,
        trainingId: res.data.trainingId,
        description: htmlContent,
      })
      this.setData({
        barTitle: res.data.trainingProgramDO.programName,
      })
      this.getShareInfo(res.data.trainingId)

      console.log(res.data.trainingProgramDO.programName)
    }
  },
  async getShareInfo(trainingId) {
    const res = await request.get(
      api.shareTrainInfo + trainingId,
      {},
      { loading: false }
    )
    if (res.httpStatus === 200) {
      this.setData({
        shareInfo: res.data,
      })

      if (res.data.posterImageUrl) {
        this.setData({
          posterSrc: res.data.posterImageUrl,
        })
      }
    }
  },
  onReady: function () {
    this.shareSheet = this.selectComponent('#shareSheet')
    this.awardModal = this.selectComponent('#awardModal')
    // if(this.awardModal){
    //   this.awardModal.show()
    // }
  },
  // 显示分享弹窗
  showShareSheet() {
    this.setData({
      showPoster: true,
      canShow: false,
    })
    this.shareSheet.show()
  },
  // 隐藏分享弹窗
  hideShareSheet() {
    let canShow = false
    if (this.data.canShow) {
      canShow = true
    }
    this.setData({
      showPoster: false,
      finishTaskShow: canShow,
    })
    this.shareSheet.hide()
  },
  // 显示分享弹窗
  showShareSheet1() {
    this.setData({
      showPoster: true,
      finishTaskShow: false,
      canShow: true,
    })
    this.shareSheet.show()
  },
  // 保存图片到相册
  savePic: function () {
    let that = this
    let { posterSrc, activityId } = this.data
    if(activityId){
      that.handleSave()
      return
    }
    wx.getImageInfo({
      src: posterSrc,
      success: function (sres) {
        wx.saveImageToPhotosAlbum({
          filePath: sres.path,
          success: function (fres) {
            that.hideShareSheet()
            wx.showToast({
              title: '保存成功',
              icon: 'success',
            })
          },
          fail: function (fres) {
            console.log(fres)
            wx.showToast({
              title: '保存失败',
              icon: 'error',
            })
          },
        })
      },
    })
  },
  // 完成打卡
  async handleFinish() {
    const patientInfo = wx.getStorageSync('patientInfo')
    let { id, trainingId } = this.data
    const res = await request.post(
      api.completeTraining,
      {
        detailId: id,
        patientId: patientInfo.id,
      },
      { loading: false }
    )
    if (res.httpStatus === 200) {
      this.init()
      this.setData({
        completeNum: res.data.completeNum,
        programName: res.data.programName,
        finishTaskShow: true,
        canShow: true,
      })
      this.getTrainDetail(id)
      const finishTaskEntrance = app.globalData.finishTaskEntrance
      // 查询是否有下一个任务
      if (finishTaskEntrance !== 4) {
        this.getHasNextTask(id, finishTaskEntrance)
      }
    }
  },
  // 补打卡
  async handleMakeup() {
    const patientInfo = wx.getStorageSync('patientInfo')
    let { id, trainingId } = this.data
    const res = await request.post(
      api.compensateTraining,
      {
        detailId: id,
        patientId: patientInfo.id,
      },
      { loading: false }
    )
    if (res.httpStatus === 200) {
      this.init()
      const finishTaskEntrance = app.globalData.finishTaskEntrance
      // 查询是否有下一个任务
      if (finishTaskEntrance !== 4) {
        this.getHasNextTask(id, finishTaskEntrance)
      }
      this.setData({
        completeNum: res.data.completeNum,
        programName: res.data.programName,
        finishTaskShow: true,
        canShow: true,
      })
      this.getTrainDetail(id)
    }
  },
  async getHasNextTask(detailId, finishTaskEntrance) {
    const hasNextRes = await request.get(api.getNextTask, {
      detailId,
      getType: finishTaskEntrance == 2 ? 2 : 1,
    })
    console.log('hasNextRes', hasNextRes)
    if (hasNextRes.httpStatus) {
      this.setData({
        hasNextData: { ...hasNextRes.data },
      })
    }
  },
  // 查看下一题
  next() {
    const { detailId, questionnaireId, trainingId, trainingType } =
      this.data.hasNextData
    let { fromOrigin, activityId } = this.data
    app.globalData.isHandleNext = 1
    handleNext = true
    if (trainingType === 1) {
      wx.redirectTo({
        url: `/pages/sceneTaskDetail/index?id=${detailId}&fromOrigin=${fromOrigin}&activityId=${activityId}`,
      })
    } else {
      wx.redirectTo({
        url: `/pages/selfAssessment/question/index?key=1&pathId=${trainingId}&id=${questionnaireId}&taskFlowId=${detailId}&fromOrigin=${fromOrigin}&activityId=${activityId}`,
      })
    }
  },
  // 关闭完成训练任务弹窗
  async handleCloseTask() {
    this.setData({
      finishTaskShow: false,
    })
    let { trainingId } = this.data
    const userId = wx.getStorageSync('userId')
    const res = await request.get(
      api.getUserActivityStatus,
      {
        userId,
        activityTrainingId: trainingId
      },
      { loading: false,message: false }
    )
    if (res.httpStatus === 200) {
      if(res.data.isMeetCondition === 1 && res.data.isFillAddress === 0){
        this.awardModal.show()
      }
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let { shareInfo, fromOrigin, activityId } = this.data
    if(fromOrigin === 1){
      const userId = wx.getStorageSync('userId')
      return {
        title: '可知成长邀您领实物好礼，包邮到家',
        path: `/pages/index/index?fromShare=practiceAward&activityId=${activityId}&userId=${userId}`,
        imageUrl:
          'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend7ac3684b69484eaebe33de50ddaebc04.png',
      }
    }
    return {
      title: shareInfo.trainingName,
      path: '/pages/sceneTrainDetail/index?trainingId=' + shareInfo.trainingId,
      imageUrl:
        shareInfo.shareImageUrl ||
        'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend5d6c29cf96f348d08c6a56d83a995686.png',
    }
  },
  // 点击返回
  handleBack() {
    if (!this.data.canShow) {
      if (app.globalData.isFirstTask) {
        wx.switchTab({
          url: '/pages/index/index',
        })
      } else {
        wx.navigateBack()
      }
      app.globalData.isFirstTask = false
    } else {
      // if(app.globalData.finishTaskEntrance === 4 || app.globalData.finishTaskEntrance === 2){
      // 	return
      // }
      // if(handleNext){
      // 	return
      // }

      let { trainingId } = this.data
      wx.setStorageSync('trainingId', trainingId)
      app.handleFinishTaskBack()
    }
  },
  // 领奖弹窗点击“再等等”
  handleCancle(){
    this.awardModal.hide()
  },
  // 领奖弹窗点击“去领奖”
  handleAward(){
    // 返回活动页面
    app.backToPath('activity/practiceAward/index')
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },
  onHide: function () {},
})
